package ro.gillardon.business.priceservice.impl.train;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

import org.apache.log4j.Logger;

import ro.gillardon.commons.Price;
import ro.gillardon.commons.enums.Currency;
import ro.gillardon.commons.logger.BTPLogger;

/**
 * Helper class for parsing values into required form.
 *
 * @author davidl
 */
public final class DBahnResultParserUtil {

  /** Non-breaking space. */
  private static final String NBSP = "\u00a0";
  /** The Constant LOG . */
  private static final Logger LOG = Logger.getLogger(DBahnResultParserUtil.class);

  /**
   * Prohibit instantiation of static class.
   */
  private DBahnResultParserUtil() {
    // prohibit instantiation of static class
  }

  /**
   * Parses the date time.
   *
   * @param dateString the date string
   * @param timeString the time string
   * @return the local date time
   */
  public static LocalDateTime parseDateTime(final String dateString, final String timeString) {
    try {
      return LocalDateTime.parse(dateString.split(" ")[1] + " " + timeString.substring(0, 5),
        DateTimeFormatter.ofPattern("dd.MM.yy HH:mm"));
    } catch (DateTimeParseException | IllegalArgumentException e) {
      BTPLogger.error(LOG, e);
      return null;
    }
  }

  /**
   * Parses the duration.
   *
   * @param text the text
   * @return the duration
   */
  public static Duration parseDuration(final String text) {
    try {
      String[] hourMinutes = text.split(":");
      return Duration.ofMinutes(60 * Integer.parseInt(hourMinutes[0]) + Integer.parseInt(hourMinutes[1]));
    } catch (ArithmeticException | NumberFormatException e) {
      BTPLogger.error(LOG, e);
      return null;
    }
  }

  /**
   * Parses the int.
   *
   * @param text the text
   * @return the integer
   */
  public static Integer parseInt(final String text) {
    try {
      return Integer.parseInt(text);
    } catch (NumberFormatException e) {
      BTPLogger.error(LOG, e);
      return null;
    }
  }

  /**
   * Parses the price.
   *
   * @param text the text
   * @return the price
   */
  public static Price parsePrice(final String text) {
    try {
      String[] tokens = text.replaceAll(NBSP, " ").split(" ");
      String price = tokens[0].replace(',', '.');
      String currency = tokens[1];
      return new Price(Double.valueOf(price), Currency.valueOf(currency));
    } catch (IllegalArgumentException e) {
      BTPLogger.error(LOG, e);
      return null;
    }
  }

  /**
   * Parses the train types.
   *
   * @param text the text
   * @return the string
   */
  public static String parseTrainTypes(final String text) {
    return text;
  }

}
